package com.ssm.property.server.controller.room;

import com.github.pagehelper.PageInfo;
import com.jee.ssm.common.support.Const;
import com.jee.ssm.common.utils.UUIDFactory;
import com.jee.ssm.common.web.json.Tip;
import com.jee.ssm.common.web.param.ParamMap;
import com.ssm.property.dao.model.building.Building;
import com.ssm.property.dao.model.residence.Residence;
import com.ssm.property.dao.model.room.Room;
import com.ssm.property.dao.model.unit.Unit;
import com.ssm.property.rpc.api.building.BuildingService;
import com.ssm.property.rpc.api.residence.ResidenceService;
import com.ssm.property.rpc.api.room.RoomService;
import com.ssm.property.rpc.api.unit.UnitService;
import com.ssm.upms.dao.model.Account;
import com.ssm.upms.log.AdminControllerLog;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 房间管理 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/room")
public class RoomController {


    /**
     * 进入房间添加页面 携带一个生成的id --> longId
     * @param model 返回的实体容器
     * @return 添加页面
     */
    @RequestMapping(value="/add")
    @RequiresPermissions("room:add")
    public String add(HttpServletRequest request, ModelMap model){
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        model.put("type",account.getType());
       /* if(account.getType()==21) {
            model.put("residence", residenceService.selectById(account.getInfoId().split(",")[1]));
        }*/
        model.put("longId", UUIDFactory.getStringId());
        return "manager/room/add";
    }


    /**
     * 批量添加住户
     * @return 添加页面
     */
    @RequestMapping(value = "/adds")
    @RequiresPermissions("room:add")
    public String adds(HttpServletRequest request, ModelMap model){
        HttpSession session = request.getSession();
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        model.put("type",account.getType());
      /*  if(account.getType()==21) {
            model.put("residence", residenceService.selectById(account.getInfoId().split(",")[1]));
        }*/
        return  "manager/room/adds";
    }


    /**
     * 进入房间编辑页面
     * @param model 返回房间的容器
     * @param id 房间id
     * @return 编辑页面
     */
    @RequestMapping(value="/edit")
    @RequiresPermissions("room:edit")
    public String edit(HttpServletRequest request, ModelMap model, @RequestParam String id) {
            HttpSession session = request.getSession();
            Account account = (Account)session.getAttribute(Const.ACCOUNT);
            model.put("type",account.getType());
            Room room=  roomService.selectById(id);
            Residence residence= residenceService.selectById(room.getResidenceId());
            Unit unit=unitService.selectById(room.getUnitId());
            model.put("unitId",unit.getId());
            model.put("unitNumber",unit.getNumber());
            model.put("buildingId",unit.getBuildingId());
            Building building=buildingService.selectById(unit.getBuildingId());
            model.put("building",building);
            model.put("residenceId",residence.getId());
            model.put("residenceCode",residence.getCode());
            model.put("data",room);
            return "manager/room/edit";
    }


    /**
     * 房间添加
     * @param room 带id的房间对象
     * @return 成功状态
     */
    @RequestMapping(value="/save")
    @ResponseBody
    @RequiresPermissions("room:add")
    @AdminControllerLog(description = "添加房间" )
    public Tip save(Room room,HttpServletRequest request)  {
        try {
            ParamMap paramMap=new ParamMap(request);
            paramMap.put("unitId",room.getUnitId());
            paramMap.put("number",room.getNumber());
            if(roomService.count(paramMap)>0){
                return  new Tip(1,"住户编号已存在");
            }
            roomService.insert(room);
            return new Tip();
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1,"添加失败！");
        }

    }



    /**
     * 批量添加住户
     * @param room 住户对象
     * @return 成功状态
     */
    @RequestMapping(value="/saves")
    @ResponseBody
    @RequiresPermissions("room:add")
    @AdminControllerLog(description = "添加住户" )
    public Tip saves(Room room,String count,String floor,HttpServletRequest request)  {
        try {
            int floorInt=Integer.parseInt(floor);
            int countInt=Integer.parseInt(count);
            ParamMap paramMap=new ParamMap(request);
            for(int i=1;i<=floorInt;i++){//楼层数
                for(int j=1;j<=countInt;j++){
                    String number="";
                    if(j<10){
                       number=i+"0"+j;
                    }else {
                        number= String.valueOf(i)+String.valueOf(j);
                    }
                    room.setId(UUIDFactory.getStringId());
                    room.setNumber(number);
                    room.setResidenceId(room.getResidenceId());
                    room.setUnitId(room.getUnitId());
                    room.setFloor(i);
                    paramMap.put("unitId",room.getUnitId());
                    paramMap.put("number",number);
                    if(roomService.count(paramMap)>0){continue;}
                    roomService.insert(room);
                }
            }
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"批量添加失败");
        }
    }


    /**
     * 根据 id 修改房间
     * @param room 带id的房间对象
     * @return 成功状态
     */
    @RequestMapping(value="/update")
    @ResponseBody
    @RequiresPermissions("room:edit")
    @AdminControllerLog(description = "修改房间" )
            public Tip update(Room room,HttpServletRequest request) {
                try {
                    String id= request.getParameter("id");
                    if(roomService.selectById(id).getNumber()!=room.getNumber()){
                        ParamMap paramMap=new ParamMap(request);
                        paramMap.put("unitId",room.getUnitId());
                        paramMap.put("number",room.getNumber());
                        if(roomService.count(paramMap)>0){
                            return  new Tip(1,"住户编号已存在");
                        }
                        room.setNumber(room.getNumber());
                    }
            roomService.updateById(room);
            return new Tip();
        } catch (Exception e) {
             e.printStackTrace();
            return new Tip(1,"修改失败！");
        }

    }


    /**
     * 根据 id 删除房间
     * @param id 房间id
     * @return 成功状态
     */
    @RequestMapping(value="/delete")
    @ResponseBody
    @RequiresPermissions("room:delete")
    @AdminControllerLog(description = "删除房间" )
    public Tip delete(@RequestParam String id) {

        try {
            roomService.deleteById(id);
        /*    userRoomService.deleteByRoomId(id);*/
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"删除失败！");
        }

    }


    /**
     * 2017年5月22日  闫增宝   批量删除userRoom相关信息
     * 根据 id 列表批量删除
     * @param ids 房间id List
     * @return 成功状态
     */
    @RequestMapping(value="/deleteByIds")
    @ResponseBody
    @RequiresPermissions("room:delete")
    @AdminControllerLog(description = "批量删除房间" )
    public Tip deleteByIds(@RequestParam("ids") List<String> ids) {

        try {
            roomService.deleteByIds(ids);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"批量删除失败！");
        }

    }


    /**
     * 根据 id 查找房间
     * @param id 房间id
     * @return 房间对象 json
     */
    @RequestMapping(value="/findJson")
    @ResponseBody
    @RequiresPermissions("room:list")
    public Room find(@RequestParam String id) {

        return roomService.selectById(id);
    }


    /**
     * 获取房间列表 获取全部 不分页
     * @param request 请求参数
     * @return 房间列表页面
     */
    @RequestMapping(value="/all")
    @RequiresPermissions("room:list")
    public String all(HttpServletRequest request, ModelMap modelMap) {

        return list(request,modelMap,1,0);
    }


    /**
     * 获取房间列表 分页
     * @param request 请求参数
     * @param page 第几页
     * @param size 每页大小
     * @return 房间列表页面
     */
    @RequestMapping(value="/list")
    @RequiresPermissions("room:list")
    public String list(HttpServletRequest request, ModelMap modelMap, Integer page, Integer size) {
        HttpSession session=request.getSession();
        Account account= (Account) session.getAttribute(Const.ACCOUNT);
        ParamMap paramMap=new ParamMap(request);
/*
        System.out.println(paramMap);
        String unitNumber= (String) paramMap.get("unitId");
        System.out.println(unitNumber);

`
        String number="";
        if(unitNumber != null && !"".equals(unitNumber)){
            unitNumber=unitNumber.trim();
            for(int i=0;i<unitNumber.length();i++){
                if(unitNumber.charAt(i)>=48 && unitNumber.charAt(i)<=57){
                    number+=unitNumber.charAt(i);
                }
            }
            System.out.println("提取后的："+number);
        }
*/
     /*   if (account.getType()==2){
            paramMap.put("estateId",account.getInfoId());
        } else if (account.getType()==21){
            if(estateService.selectById(account.getInfoId().split(",")[0]) != null){
                paramMap.put("estateId",account.getInfoId().split(",")[0]);
            }
            paramMap.put("residenceId",account.getInfoId().split(",")[1]);
        } else if(account.getType()==5){
            List<PoliceResidence> policeResidenceList= policeResidenceService.findByPoliceId(account.getInfoId());
            List<String> policeIdList=new ArrayList<String>();
            if(policeResidenceList.size()>0){
                for(PoliceResidence pr:policeResidenceList){
                    policeIdList.add(pr.getResidenceId());
                }
            }else {
                policeIdList.add("0");
            }
            paramMap.put("policeIdList", policeIdList);
        }*/
        PageInfo<Room> pageInfo=roomService.list(paramMap,page,size);
        for (Room room:pageInfo.getList()){
            room.setUnit(unitService.selectById(room.getUnitId()));
            room.setResidence(residenceService.selectById(room.getResidenceId()));
            room.setBuilding(buildingService.selectById(room.getFacilities()));
        }
        List<Residence> residences = residenceService.listWithoutPage(paramMap);//搜索下拉框选择小区
        modelMap.put("residences",residences);//搜索下拉框选择小区
        modelMap.put("type",account.getType());
        modelMap.put("pageInfo",pageInfo);
        modelMap.putAll(paramMap);
        return "manager/room/list";
    }



    /**
     * 获取住户列表
     * @return 住户列表页面
     */
    @RequestMapping(value="/checklist")
    @RequiresPermissions("room:list")
    public String checklist(ModelMap modelMap, @RequestParam String unitId) {
            List<Room> list=roomService.chooseList(unitId);
            for(Room room:list){
                room.setUnit(unitService.selectById(room.getUnitId()));
            }
            modelMap.put("list",list);
            return  "manager/room/chooseRoom";
    }

/*

    */
/**
     * 单元入住状态统计
     * @return
     *//*

    @RequestMapping(value = "/countRoom")
    @ResponseBody
    public Map<String, Object> countRoom(HttpServletRequest request) throws Exception {
        HttpSession session=request.getSession();
        Account account= (Account) session.getAttribute(Const.ACCOUNT);

        Map<String, Object> map = new HashMap<String, Object>();
        Room room = new Room();
        if (account.getType()==21){
          room.setResidenceId(account.getInfoId().split(",")[1]);
        }else if(account.getType()==2){
            room.setIntro(account.getInfoId());
        }else if(account.getType()==5){
            room.setPoliceId(account.getInfoId());
        }
        List<Room> queryAllRoom = roomService.findAllRoom(room);
        int length = queryAllRoom.size();
        String[] nameArray = new String[length];

        List<Echat> list = new ArrayList<Echat>();
        for(int i = 0 ;i<nameArray.length; i++  ){
            nameArray [i] = queryAllRoom.get(i).getIntro()+"单元";
        }

        room.setStatus("1");
        for(Room community : queryAllRoom){
            room.setUnitId(community.getUnitId());
            Room re = roomService.countNumber(room);
            Echat count= new Echat();
            count.setValue(re.getIntro());//数量
            count.setName(community.getIntro()+"单元");
            list.add(count);
        }

        List<Echat> list2 = new ArrayList<Echat>();
        room.setStatus("0");
        for(Room community2 : queryAllRoom){
            room.setUnitId(community2.getUnitId());
            Room re = roomService.countNumber3(room);
            Echat count2= new Echat();
            count2.setValue(re.getIntro());//数量
            count2.setName(community2.getIntro()+"单元");
            list2.add(count2);
        }


        map.put("value",list);
        map.put("value2",list2);
        map.put("name",nameArray);
        return map;
    }

    */
/**
     * 小区房屋数量统计
     * @return
     *//*

    @RequestMapping(value = "/countRoom2")
    @ResponseBody
    public Map<String, Object> countRoom2() throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();

        Room room = new Room();

        List<Room> queryAllRoom = roomService.findAllRoom2();
        int length = queryAllRoom.size();
        String[] nameArray = new String[length];

        List<Echat> list = new ArrayList<Echat>();
        for(int i = 0 ;i<nameArray.length; i++  ){
            nameArray [i] = queryAllRoom.get(i).getStatus();
        }
        for(Room community : queryAllRoom){
            room.setResidenceId(community.getResidenceId());
            Room re = roomService.countNumber2(room);
            Echat count= new Echat();
            count.setValue(re.getIntro());//数量
            count.setName(community.getStatus());

            list.add(count);
        }
        map.put("value",list);
        map.put("name",nameArray);
        return map;
    }

    */
/**
     * 获取房间下的住户
     * @param request 请求参数
     * @return 住户列表
     *//*

    @RequestMapping(value="/user")
    public String user(HttpServletRequest request, ModelMap modelMap, @RequestParam String id) {
        HttpSession session=request.getSession();
        Account account= (Account) session.getAttribute(Const.ACCOUNT);
        ParamMap paramMap=new ParamMap(request);
        User record =new User();
        record.setId(id);
        List<User> pageInfo=userService.userList(record);
        modelMap.put("type",account.getType());
        modelMap.put("pageInfo",pageInfo);
        modelMap.putAll(paramMap);
        return "manager/room/user";
    }
*/

    /**
     * 获取某房间下的开门记录
     * @param request 请求参数
     * @return 开门记录列表
     */
/*    @RequestMapping(value="/record")
    public String record(HttpServletRequest request, ModelMap modelMap, @RequestParam String id) {
        HttpSession session=request.getSession();
        Account account= (Account) session.getAttribute(Const.ACCOUNT);
        ParamMap paramMap=new ParamMap(request);
        Record record =new Record();
        record.setRoomId(id);
        List <Record> pageInfo=recordService.openList(record);
        modelMap.put("pageInfo",pageInfo);
        modelMap.putAll(paramMap);
        return "manager/room/record";
    }*/


    /**
     * 2017年5月22日 闫增宝
     * 房屋数据导出
     * @param request
     * @param response
     * @param session
     * @throws IOException
     */
    @RequestMapping(value = "/exportEcxel")
    @RequiresPermissions("room:exportEcxel")
    public void exportEcxel(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        ParamMap paramMap = new ParamMap(request);
        Account account = (Account)session.getAttribute(Const.ACCOUNT);
        if(account.getType() == 2) {
            paramMap.put("estateId", account.getInfoId());
        }else if (account.getType() == 21){
            paramMap.put("residenceId",account.getInfoId().split(",")[1]);
        }/*else if(account.getType() == 5){
            List<PoliceResidence> policeResidenceList= policeResidenceService.findByPoliceId(account.getInfoId());
            List<String> policeIdList=new ArrayList<String>();
            if(policeResidenceList.size()>0){
                for(PoliceResidence pr:policeResidenceList){
                    policeIdList.add(pr.getResidenceId());
                }
            }else {
                policeIdList.add("0");
            }
            paramMap.put("policeIdList", policeIdList);
        }*/
        List<Room> list = roomService.listWithoutPage(paramMap);
        String originFileUrl = request.getServletContext().getRealPath("/download/info.xlsx");
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), Room.class, list);
        FileOutputStream fos = new FileOutputStream(originFileUrl);
        workbook.write(fos);

        String fileName = "房屋导出.xls";
        fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        //设置文件MIME类型
        response.setContentType(request.getServletContext().getMimeType(fileName));
        //设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //读取文件
        InputStream in = new FileInputStream(originFileUrl);
        OutputStream out = response.getOutputStream();

        //写文件
        int b;
        while((b=in.read()) != -1) {
            out.write(b);
        }
        fos.close();
        in.close();
        out.close();
    }



    //---------------------------- property -------------------------------

    @Resource
    private RoomService roomService;

 /*   @Resource
    private RecordService recordService;

    @Resource
    private UserService userService;*/

    @Resource
    private ResidenceService residenceService;

    @Resource
    private BuildingService buildingService;

    @Resource
    private UnitService unitService;

/*    @Resource
    private PoliceResidenceService policeResidenceService;

    @Resource
    private UserRoomService userRoomService;

    @Resource
    private EstateService estateService;*/

}
